/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.esp.webalbum.ui;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.esp.webalbum.image.DiskLruCache;
import com.esp.webalbum.image.ImageCache;
import com.esp.webalbum.image.ImageFetcher;
import com.esp.webalbum.image.ImageResizer;
import com.esp.webalbum.image.ImageWorker;
import com.esp.webalbum.image.Images;
import com.esp.webalbum.image.Utils;
import com.esp.webalbum.utils.Log;


public class ImageDetailActivity extends FragmentActivity implements OnClickListener {
	
	private static String TAG = ImageDetailActivity.class.getCanonicalName();
	
	private static final String IMAGE_CACHE_DIR = "images";
	public static final String EXTRA_IMAGE = "extra_image";
	
	private ImagePagerAdapter mAdapter;
	private ImageResizer mImageWorker;
	private ViewPager mPager;
	
	private TextView textView_PageNo;
	
	private Button btn_next,btn_previous;
	
	public int Index = -1;
	
	/**
	 * 60000 = 1 Min
	 */
	private long longMiliSeconds = (60000/60) * 5;
	
	
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.image_detail_pager);
	    
	    textView_PageNo =(TextView)findViewById(R.id.textView_PageNo);
	    textView_PageNo.setOnClickListener(this);
	    btn_next = (Button)findViewById(R.id.btn_next);
	    btn_previous = (Button)findViewById(R.id.btn_previous);
	    btn_next.setOnClickListener(this);
	    btn_previous.setOnClickListener(this);
	    
	    // Fetch screen height and width, to use as our max size when loading images as this
		// activity runs full screen
		final DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		final int height = displaymetrics.heightPixels;
		final int width = displaymetrics.widthPixels;
		final int longest = height > width ? height : width;
			
		// The ImageWorker takes care of loading images into our ImageView children asynchronously
		mImageWorker = new ImageFetcher(this, longest);
		mImageWorker.setAdapter(Images.imageWorkerUrlsAdapter);
		mImageWorker.setImageCache(ImageCache.findOrCreateCache(this, IMAGE_CACHE_DIR));
		mImageWorker.setImageFadeIn(false);
		
		// Set up ViewPager and backing adapter
		mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),
		        mImageWorker.getAdapter().getSize());
	
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);
		mPager.setPageMargin((int) getResources().getDimension(R.dimen.image_detail_pager_margin));
		textView_PageNo.setText((mPager.getCurrentItem()+ 1) + "/"+ mImageWorker.getAdapter().getSize());
		mPager.setOnPageChangeListener(new OnPageChangeListener() 
		{
		
			public void onPageSelected(int position) {
				Index = position;
				textView_PageNo.setText((position + 1) + "/"+ mImageWorker.getAdapter().getSize());
			}
			
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	
	
		// Set up activity to go full screen
		getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
		
		// Enable some additional newer visibility and ActionBar features to create a more immersive
		// photo viewing experience
		if (Utils.hasActionBar()) 
		{
		    final ActionBar actionBar = getActionBar();
		
		    // Enable "up" navigation on ActionBar icon and hide title text
		    actionBar.setDisplayHomeAsUpEnabled(true);
		    actionBar.setDisplayShowTitleEnabled(false);
		
		    // Start low profile mode and hide ActionBar
		    mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
		    actionBar.hide();
		
		    // Hide and show the ActionBar as the visibility changes
		    mPager.setOnSystemUiVisibilityChangeListener(
		            new View.OnSystemUiVisibilityChangeListener() {
	                
	                public void onSystemUiVisibilityChange(int vis) {
	                    if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
	                        actionBar.hide();
	                    } else {
	                        actionBar.show();
	                    }
	                }
	            });
		}
	
		
		
	// Set the current item based on the extra passed in to this activity
	    final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
	    if (extraCurrentItem != -1) {
	    	Index = extraCurrentItem;
	        mPager.setCurrentItem(Index);
	    }
	    final Object data = getLastCustomNonConfigurationInstance();
	    if(data != null){
	    	Index =(Integer)data;
	    	Log.verbose(TAG," getLastCustomNonConfigurationInstance" + Index);
	    }
	}
	
	/** 
	 * When Orientation change keep Index value 
	 */
	@Override
	public Object onRetainCustomNonConfigurationInstance() {
		return Index;
	}
	@Override
	protected void onResume() {
		super.onResume();
		mPlayerHandler.removeCallbacks(UpdateImageView);
		Log.verbose(TAG," First removeCallbacks  ");
		mPlayerHandler.postDelayed(UpdateImageView,longMiliSeconds);
		
	}
	
	@Override
	protected void onDestroy() {
		 
		mPlayerHandler.removeCallbacks(UpdateImageView);	
		Log.debug(TAG, " Handler destroying ");
		super.onDestroy();
	}
	
	/**
	 * Called by the ViewPager child fragments to load images via the one ImageWorker
	 *
	 * @return
	 */
	public ImageWorker getImageWorker() {
	    return mImageWorker;
	}
	
	/**
	 * The main adapter that backs the ViewPager. A subclass of FragmentStatePagerAdapter as there
	 * could be a large number of items in the ViewPager and we don't want to retain them all in
	 * memory at once but create/destroy them on the fly.
	 */
	private class ImagePagerAdapter extends FragmentStatePagerAdapter {
	    private final int mSize;
	
	    public ImagePagerAdapter(FragmentManager fm, int size) {
	        super(fm);
	        mSize = size;
	    }
	
	    @Override
	    public int getCount() {
	        return mSize;
	    }
	
	    @Override
	    public Fragment getItem(int position) {
	    	return ImageDetailFragment.newInstance(position);
	    }
	
	    @Override
	    public void destroyItem(ViewGroup container, int position, Object object) {
	        final ImageDetailFragment fragment = (ImageDetailFragment) object;
	        // As the item gets destroyed we try and cancel any existing work.
	        fragment.cancelWork();
	        super.destroyItem(container, position, object);
	    }
	    
	}
	
	/**
	 * Set on the ImageView in the ViewPager children fragments, to enable/disable low profile mode
	 * when the ImageView is touched.
	 */
	@SuppressLint("NewApi")
	
	public void onClick(View v) {
		
	   /* final int vis = mPager.getSystemUiVisibility();
	if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
	    mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
	} else {
	    mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
	}*/
	    
	    switch (v.getId()) {
		case R.id.btn_next:
			
				//mPlayerHandler.removeCallbacks(UpdateImageView);
				if(Index < mImageWorker.getAdapter().getSize())
				{ 	
					Index++;
					mPager.setCurrentItem(Index);
				}
					
			break;
		case R.id.btn_previous:
				//mPlayerHandler.removeCallbacks(UpdateImageView);
				if(Index > 0){
					Index --;
					mPager.setCurrentItem(Index);
				}
			break;	
		case R.id.textView_PageNo:
			Log.verbose(TAG," TAP ON TEXT VIEW  ");
			mPlayerHandler.removeCallbacks(UpdateImageView);
			
			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle("Title");
			alert.setMessage("Message");

			// Set an EditText view to get user input 
			final EditText input = new EditText(this);
			input.setInputType(InputType.TYPE_CLASS_NUMBER);
			alert.setView(input);

			alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int whichButton) 
				{
					
					String valueIndex = input.getText().toString();
					// set Index value and start Runner
					Log.verbose(TAG," INDEX NUMBER  SEARCH " + Integer.parseInt(valueIndex));
					if(Integer.parseInt(valueIndex)> 0 && Integer.parseInt(valueIndex)<= mImageWorker.getAdapter().getSize())
					{
						Index = Integer.parseInt(valueIndex) - 1;
						mPlayerHandler.postDelayed(UpdateImageView,longMiliSeconds);
						dialog.dismiss();
					}
					
				}
			});

			alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
			{
			  public void onClick(DialogInterface dialog, int whichButton)
			  {
				  if(!textView_PageNo.getText().equals(""))
				  {
					  String lastPosition[] = textView_PageNo.getText().toString().split("/");
					  Log.verbose(TAG," LAST INDEX NUMBER " + Integer.parseInt(lastPosition[0]));
					  Index = Integer.parseInt(lastPosition[0]) - 1;
					  mPlayerHandler.postDelayed(UpdateImageView,longMiliSeconds);
					  dialog.dismiss();
				  }
				  
			  }
			});

			alert.show();
			
			
			
			break;
		default:
			break;
		}
	}
	
	
	/**
	 * HANDLER FOR IMAGE PLAYER
	 */
		
	private final Handler mPlayerHandler = new Handler();
	
	private Runnable UpdateImageView = new Runnable() {
		
	    	public void run() {
	    		
	    		Log.verbose(TAG," IMAGE PLAYER RUNNING " + Index + "Total Image " + mImageWorker.getAdapter().getSize());
	    		if(Index > -1 && Index < mImageWorker.getAdapter().getSize())
	    		{
	    			mPager.setCurrentItem(Index);
	    			Index++;
					mPlayerHandler.postDelayed(this,longMiliSeconds); 

	    		}else if(Index == mImageWorker.getAdapter().getSize()){
	    			Index = 0;
	    			mPager.setCurrentItem(Index);
	    			mPlayerHandler.postDelayed(this,longMiliSeconds);
	    		}
	    		
	    	}
	 };
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		
		case R.id.set_as:
			
				Log.verbose(TAG, " ON MENU CLICK ");
				mPlayerHandler.removeCallbacks(UpdateImageView);
				AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetailActivity.this);
				builder.setMessage("want to set as wallpaper ? ")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
				       {
				           public void onClick(DialogInterface dialog, int id) 
				           {
				        	   
					            AsyncTask<Void, Void, Integer> mWallpaperService = new AsyncTask<Void, Void, Integer>() {
					            	
					            	ProgressDialog mProgressDialog;
					            	
					            	@Override
									protected void onPreExecute() {
										super.onPreExecute();
										
										mProgressDialog = new ProgressDialog(ImageDetailActivity.this);
					            		mProgressDialog.setCancelable(false);
					            		mProgressDialog.setMessage("Please wait...");
					            		mProgressDialog.show();
									}
					            	
									@Override
									protected Integer doInBackground(Void... params) {
										int Result = 0;
										try
										{
											
											// Get WallpaperManager instance (in your Activity or Service):
											WallpaperManager wallpaperManager = WallpaperManager.getInstance(ImageDetailActivity.this);
											// Get your image drawable:
											Log.verbose(TAG,"[FETCH IMAGE]" + (Index -1) + " | "+ SplashScreen.arrayListImageBean.get(Index -1).getStrAbsPath());
											
											final int height = wallpaperManager.getDesiredMinimumHeight();
											final int width = wallpaperManager.getDesiredMinimumWidth();
											
											ImageCache mImageCache = ImageCache.findOrCreateCache(ImageDetailActivity.this, IMAGE_CACHE_DIR);
											Bitmap wallpaper  = mImageCache.getBitmapFromDiskCache(SplashScreen.arrayListImageBean.get(Index -1).getStrAbsPath());
											Bitmap resizedbitmap = Bitmap.createScaledBitmap(wallpaper, width, height, true);
											wallpaperManager.setBitmap(resizedbitmap);
											Log.verbose(TAG, " SET AS WALLPAPER ");
											
											
											
											
								                
											
										}catch (Exception e) {
											e.printStackTrace();
											Result = -1;
										}
										
										return Result;
									}
									
									@Override
					            	protected void onPostExecute(Integer result) {
					            		super.onPostExecute(result);
					            		mProgressDialog.dismiss();
					            	}
								};
								
								mWallpaperService.execute();
				           }
				           
				       }).setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				return true;
				
		case R.id.clear_cache: 
			
				final ImageCache cache = mImageWorker.getImageCache();
                if (cache != null) {
                    mImageWorker.getImageCache().clearCaches();
                    DiskLruCache.clearCache(this, ImageFetcher.HTTP_CACHE_DIR);
                    Toast.makeText(this,"catch clear",
                            Toast.LENGTH_SHORT).show();
                }
                
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	 
	 
}
